package com.lw.leetcode.node;

/**
 * 979. 在二叉树中分配硬币
 *
 * @Author liw
 * @Date 2021/5/20 16:41
 * @Version 1.0
 */
public class DistributeCoins {
    int sum = 0;
    public int distributeCoins(TreeNode root) {
        find(root);
        return sum;
    }

    private int find(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int l = find(node.left);
        int r = find(node.right);
        int count = node.val + l + r;
        int value = count - 1;
        if (value < 0) {
            sum -= value;
        } else {
            sum += value;
        }
        return value;
    }
}
